package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.pojo.Setmeal;
import com.itheima.service.MemberService;
import com.itheima.utils.DateUtils;
import com.itheima.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 处理会员相关操作
 */

@RestController
@RequestMapping("/member")
public class MemberController {
    @Autowired
    private JedisPool jedisPool;

    @Reference
    private MemberService memberService;

    //手机号快速登录
    @RequestMapping("/login")
    public Result login(HttpServletRequest request, HttpServletResponse response, @RequestBody Map map) throws Exception{
        String telephone = (String) map.get("telephone");
        String validateCode = (String) map.get("validateCode");
        //从Redis中获取保存的验证码
        String validateCodeInRedis = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);
        if(validateCodeInRedis != null && validateCode != null && validateCode.equals(validateCodeInRedis)){
            //验证码输入正确
            //判断当前用户是否为会员（查询会员表来确定）
            Member member = memberService.findByTelephone(telephone);
            if(member == null){
                //不是会员，自动完成注册（自动将当前用户信息保存到会员表）
                member.setRegTime(new Date());
                member.setPhoneNumber(telephone);
                memberService.add(member);
            }
            //向客户端浏览器写入Cookie，内容为手机号


            Cookie cookie = new Cookie("login_member_telephone",telephone);
            cookie.setPath("/");
            cookie.setMaxAge(60*60*24*30);
            response.addCookie(cookie);

            //将会员信息保存到Redis
            String json = JSON.toJSON(member).toString();
            Jedis resource = jedisPool.getResource();
            resource.setex(telephone,60*60*24,json);
            return new Result(true,MessageConstant.LOGIN_SUCCESS);
        }else{
            //验证码输入错误
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
    }

    /*
     * 1.使用cookie获取当前用户标识，之后查询redis确认用户处于登录状态后显示当前用户的所有信息
     * 2.可改造cookie存储方式为密文，可在服务端使用RSA、AES或DES等算法进行加解密
     * 3.显示用户信息页面支持编辑，关键信息如绑定手机号、密码的编辑需要分别单独验证
     *
     * 判断是否登录,登录后返回数据,页面显示
     * 修改
     *
     * */
    @RequestMapping("/judge")
    public Result judge(HttpServletRequest request, HttpServletResponse response,Integer id){

        //读取Cookie
        Cookie[] cookies = request.getCookies();
        String name = null;
        String value = null;
        Member member = null;
        if(cookies!=null){
            for (Cookie cookie : cookies) {
                name = cookie.getName();
                value = cookie.getValue();//获取登录时的手机号
            }

            //判断用户是否登录
            if(jedisPool.getResource().get(value) !=null){
                member = memberService.findByTelephone(value);
            }

            return new Result(true,MessageConstant.GET_USERNAME_SUCCESS,member);
        }else{
            return new Result(false,MessageConstant.GET_USERNAME_FAIL);
        }
    }


    @RequestMapping("/edit")//完善个人信息
    public Result edit(Member member){
        try {
            memberService.edit(member);
            return new Result(true,MessageConstant.EDIT_MEMBER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.EDIT_MEMBER_FAIL);
        }
    }

    /*
     * 1.提供根据日期范围查询当前会员历史预约记录的功能
     * 2.预约记录包括当前会员所有预约记录基本信息和每条预约记录的预约详情（包括预约机构地址、套餐等）
     *
     */
    @RequestMapping("/findByDateAndId")
    public Result findByDateAndId(String date1,String date2,Integer id){

        try {
            List<Setmeal> list = memberService.findByDateAndId(date1,date2,id);
            return new Result(true,MessageConstant.QUERY_SETMEAL_SUCCESS,list);
        } catch (Exception e) {

            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_SETMEAL_FAIL);
        }
    }

    //用户使用登录
    @RequestMapping("/loginByPwd")
    public Result loginByPwd(@RequestBody Map map, HttpServletResponse resp) {
        //获取用户输入的手机号和密码
        String telephone = (String) map.get("telephone");
        String password = (String) map.get("password");
        //通过手机号码和密码查询
        Member member = memberService.findByTelAndPassword(map);


        if (member != null) {
            Cookie cookie = new Cookie("telephone", telephone);
            Cookie cookie1 = new Cookie("password", MD5Utils.md5(password));
            cookie.setPath("/");
            cookie.setMaxAge(60 * 60 * 24 * 30);
            //将响应添加Cookie
            resp.addCookie(cookie);
            resp.addCookie(cookie1);
            //将会员信息转换为json类型
            String json = JSON.toJSON(member).toString();
            //将会员信息添加到redis中
            Jedis resource = jedisPool.getResource();
            resource.setex(telephone, 60 * 60 *24 , json);
            resource.close();

            //返回结果
            return new Result(true, MessageConstant.LOGIN_SUCCESS);
        }
        return new Result(false, MessageConstant.LOGIN_FAIL_PASSWORD);
    }



    /*
     * author:苏林
     */


    /*基本信息查看完善(包含拓展)
      1.点击个人中心,跳转到,个人中心界面
      2.点击基本信息,跳转到详细信息页面,并查询出来用户的信息(findByTelephone)
      3.完善(修改)个人信息(edit)
    */

    /*判断用户是否登录,获取id
     *查询数据,进行页面数据的回显*/

    @RequestMapping("/checkIsLogin")
    public Result checkIsLogin(HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        String value = null;
        for (Cookie cookie : cookies) {
            value = cookie.getValue();
        }
        if(value!=null){
            //根据手机号查询数据库
            Member byTelephone = memberService.findByTelephone(value);
            return new Result(true,MessageConstant.QUERY_LOGIN_SUCCESS,byTelephone);
        }else{
            return new Result(false,MessageConstant.QUERY_LOGIN_FAIL);
        }
    }

    //完善个人信息
    @RequestMapping("/editMemberInfo")
    public Result editMemberInfo(@RequestBody Member member){
        try {
            memberService.editMemberInfo(member);
            return new Result(true,MessageConstant.EDIT_MEMBER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.EDIT_MEMBER_FAIL);
        }
    }


     /*1.根据输入的时间和用户ID来查询出信息(展示体检人和套餐两个信息)(findByDateAndId)
       2.点击查询出来的记录,进行详细信息查看,
       包括套餐信息和预约人,预约方式,预约时间,到诊情况,到诊时间,到诊情况,地址
       跳转到套餐页面的的按钮(findById)
     */


    //查询所有
    @RequestMapping("/findAll")
    public Result findAll(HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        String telephone = null;
        for (Cookie cookie : cookies) {
            telephone = cookie.getValue();
        }
        if(telephone!=null){

            List<Map<String, String>> list = memberService.findAll(telephone);

            return new Result(true,MessageConstant.QUERY_ORDER_SUCCESS,list);
        }else{
            return new Result(false,MessageConstant.QUERY_ORDER_FAIL);
        }
    }

    //按照输入的时间段来查询该用户的历史记录
    @RequestMapping("/findByDateAndTelephone")
    public Result findByDateAndTelephone(String startDate,String endDate,HttpServletRequest request){

        Cookie[] cookies = request.getCookies();
        String telephone = null;
        for (Cookie cookie : cookies) {
            telephone = cookie.getValue();
        }
        if(telephone!=null){
            List<Map<String, String>> list = memberService.findByDateAndTelephone(startDate,endDate,telephone);
            return new Result(true,MessageConstant.QUERY_SETMEAL_SUCCESS,list);
        }else{
            return new Result(false,MessageConstant.QUERY_SETMEAL_FAIL);
        }
    }


    //查询预约详情(OrderDetail套餐信息和预约人,预约方式,预约时间,到诊情况,到诊时间,到诊情况,地址)
    @RequestMapping("/findDetail")
    public Result findDetail(Integer orderId){
        try {
            Map<String,String> map = memberService.findDetail(orderId);
            return new Result(true,MessageConstant.QUERY_MEMBER_SUCCESS,map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_MEMBER_FAIL);
        }
    }

}
